<template>
	<view class="flex align-center justify-between" style="width: 100%;">
		<picker @change="handleChange" :value="selectedIndex" :range="countryLabels">
			{{ selectedLabel || placeholder }}
		</picker>
		<uv-icon v-if="selectedLabel" name="close-circle" @click="clear"></uv-icon>

	</view>
</template>

<script>
	export default {
		props: {
			options: {
				type: Array,
				required: true,
			},
			value: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				currentValue: '', // 当前选中的 value 值，默认为 Japan
				selectedLabel: '', // 当前选中的 label 值，默认为空
				selectedIndex: 0, // 默认选中的索引
				countryOptions: [{
						value: 'china',
						label: '中国'
					},
					{
						value: 'usa',
						label: '美国'
					},
					{
						value: 'japan',
						label: '日本'
					}
				],
				placeholder: '请选择',
			};
		},
		watch: {
			value(newValue) {
				this.currentValue = newValue
				this.setInitialSelection();
			},
			options(newOptions) {
				this.countryOptions = newOptions
			},
		},
		computed: {
			countryLabels() {
				return this.countryOptions?.map(option => option.label);
			}
		},
		created() {
			// 在组件创建时根据 currentValue 设置 selectedIndex 和 selectedLabel
			this.countryOptions = this.options
			this.currentValue = this.value
			this.setInitialSelection();
		},
		methods: {
			setInitialSelection() {
				// 根据 currentValue 设置 selectedIndex 和 selectedLabel
				for (let i = 0; i < this.countryOptions?.length; i++) {
					if (this.countryOptions[i].value === this.currentValue) {
						this.selectedIndex = i;
						this.selectedLabel = this.countryOptions[i].label;
						break;
					}
				}
			},
			handleChange(event) {
				this.selectedIndex = event.detail.value;
				this.currentValue = this.countryOptions[this.selectedIndex].value;
				this.selectedLabel = this.countryOptions[this.selectedIndex].label;
				this.$emit('selectedValue', this.currentValue);
				// console.log('selectedValue:', this.currentValue);
				// 这里你可以添加其他逻辑，比如将选择的值发送到服务器等
			},
			clear() {
				this.currentValue = ''
				this.selectedLabel = ''
				this.selectedIndex = 0
				this.$emit('selectedValue', '');

			}
		},
	};
</script>